import Router from 'koa-router'
import Redis from 'koa-redis'
import nodeMailer from 'nodemailer'
import User from '../dbs/modules/users'
import Passport from './utils/passport'
import Email from '../dbs/config'
import axios from './utils/axios'

let router = new Router({
  prefix: '/users'
})

// 声明变量获取redis客户端
let Store = new Redis().client

router.post('/signup', async (ctx) => {
  const {
    username,
    password,
    email,
    code
  } = ctx.request.body

  //  校验验证码、过期时间
  if (code) {
    const saveCode = await Store.hget(`nodemail:${username}`, 'code')
    const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
    if (saveCode === code) {
      if (new Date().getTime() - saveExpire > 0) {
        ctx.body = {
          success: false,
          msg: '验证码已过期'
        }
        return false
      }
    } else {
      ctx.body = {
        success: false,
        msg: '验证码错误'
      }
    }
  } else {
    ctx.body = {
      success: false,
      msg: '请填写验证码'
    }
  }

  //  账户校验
  let user = await User.findOne({
    username
  })
  //  user.length    user == null    error   so  this
  if (user != null) {
    ctx.body = {
      success: false,
      msg: '该用户已被注册'
    }
    return false
  }

  let nuser = await User.create({
    username,
    password,
    email
  })
  if (nuser) {
    let res = await axios.post('/users/signin', {
      username,
      password
    })
    if (res.data.success) {
      ctx.body = {
        success: true,
        msg: '注册成功'
      }
    } else {
      ctx.body = {
        success: false,
        msg: 'error'
      }
    }
  } else {
    ctx.body = {
      success: false,
      msg: '注册失败'
    }
  }
})

router.post('/signin', async (ctx, next) => {
  return Passport.authenticate('local', function (err, user, info, status) {
    if (err) {
      ctx.body = {
        success: false,
        msg: err
      }
    } else {
      if (user) {
        ctx.body = {
          success: true,
          msg: '登录成功',
          user
        }
        return ctx.login(user)
      } else {
        ctx.body = {
          success: false,
          msg: info
        }
      }
    }
  })(ctx, next)
})

// 验证码
router.post('/verify', async (ctx, next) => {
  let {
    username
  } = ctx.request.body
  // 验证码过期时间
  const saveExpire = Store.hget(`nodemail:${username}`, 'expire')
  if (saveExpire && new Date().getTime() - saveExpire < 0) {
    ctx.body = {
      success: false,
      msg: '请求过于频繁'
    }
    return false
  }

  // 发邮件设置
  let transporter = nodeMailer.createTransport({
    host: Email.smtp.host,
    port: 587,
    secure: false,
    auth: {
      user: Email.smtp.user,
      pass: Email.smtp.pass
    }
  })

  // 接收方
  let ko = {
    code: Email.smtp.code(),
    expire: Email.smtp.expire(),
    email: ctx.request.body.email,
    user: ctx.request.body.username
  }

  // 邮件显示内容
  let mailOptions = {
    from: `"认证邮箱" <${Email.smtp.user}>`,
    to: ko.email,
    subject: 'Chengpeng Test Demo Koa2 + Ssr',
    html: `Bomm, Boom, Boom, 您的验证码为${ko.code}`
  }

  await transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return console.log('error')
    } else {
      Store.hmset(`nodemail:${ko.user}`, 'code', ko.code, 'expire', ko.expire, 'email', ko.email)
    }
  })

  ctx.body = {
    success: true,
    msg: '验证码已发送'
  }
})

// 退出
router.get('/exit', async (ctx, next) => {
  await ctx.logout()
  // 二次验证，检查现在是不是注销了状态
  if (!ctx.isAuthenticated()) {
    ctx.body = {
      success: true,
    }
  } else {
    ctx.body = {
      success: false,
    }
  }
})
// 获取用户名
router.get('/getUser', async (ctx) => {
  //isAuthenticated()， 是passport内部固定的的api，
  // 判断用户是否登录
  if (ctx.isAuthenticated()) {
    // 我们的passport会把我们的用户信息的session放到session对象里面去，ctx这个上下文对象中session就有passport相关信息，所以我们的passport是存储在这个session中的
    // 如果它是登录状态的话，session中一定有passport，passport中一定有user
    const {
      username,
      email
    } = ctx.session.passport.user
    ctx.body = {
      user: username,
      email,
    }
  } else {
    // 如果用户没有登录
    ctx.body = {
      user: '',
      email: '',
    }
  }
})

export default router
